import http from "../http";
import { defineStore } from "pinia";
import { ref } from "vue";

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useCounterStore = defineStore("counter", () => {
  const token = ref<string>("");
  const userInfo = ref<any>({});

  // 获取列表
  const get_list = async (sql, dbName) => {
    console.log(userInfo.value);

    const res = await http.corsApi("/", "post", {
      packID: "123456",
      packageType: "adminSql",
      packageContent: {
        AgentUserName: userInfo.value.username,
        AgentUserPassword: userInfo.value.password,
        sql: sql,
        dbName: dbName,
      },
    });

    if (res.packageContent) {
      // console.log(JSON.parse(res.packageContent.packageMsg));
    }

    return JSON.parse(res.packageContent.packageMsg) || []
  };

  // 修改列表
  const edit_table = async (sql, dbName) => {
    console.log(sql);

    const res = await http.corsApi("/", "post", {
      packID: "123456",
      packageType: "adminSql",
      packageContent: {
        AgentUserName: userInfo.value.username,
        AgentUserPassword: userInfo.value.password,
        sql: sql,
        dbName: dbName,
      },
    });

    return res.packageContent;
  };

  // 拼接sql语句
  const formart_sql = (obj) => {
    // console.log(arr, obj);
    let keys_arr = Object.keys(obj);
    let str = "";
    for (var i = 0; i < keys_arr.length; i++) {
      if (i == keys_arr.length - 1) {
        if (obj[keys_arr[i]] == null) {
          str += `${keys_arr[i]}=${obj[keys_arr[i]]}`;
        } else {
          str += `${keys_arr[i]}='${obj[keys_arr[i]]}'`;
        }
      } else {
        if (obj[keys_arr[i]] == null) {
          str += `${keys_arr[i]}=${obj[keys_arr[i]]},`;
        } else {
          str += `${keys_arr[i]}='${obj[keys_arr[i]]}',`;
        }
      }
    }

    return str;
  };

  // 删除sql语句
  const delete_sql = async(sql, dbName) => {
    // DELETE FROM agentuser WHERE AgentUserName = 'admin77'

    const res = await http.corsApi("/", "post", {
      packID: "123456",
      packageType: "adminSql",
      packageContent: {
        AgentUserName: userInfo.value.username,
        AgentUserPassword: userInfo.value.password,
        sql: sql,
        dbName: dbName,
      },
    });

    return res.packageContent;
  };

  return {
    token,
    userInfo,
    get_list,
    edit_table,
    formart_sql,
    delete_sql,
  };
});
